Basic Principles

1. Overview of Mathematica Features. Mathematica as a Calculator.

You can get a lot of information from the Help Browser (to access it press F1 or use the Help menu).

One  can use Mathematica just like a calculator: one types in questions, and Mathematica returns back answers.  Just press SHIFT + ENTER (RETURN) to tell Mathematica to evaluate the input you have given it.

Example.

2+2

( press SHIFT + ENTER after putting the cursor after 2 + 2 to see the output)

2+2

With a text - based interface, you interact with Mathematica just by typing successive lines of input, and getting back successive lines of output on your screen.

At each stage, Mathematica prints a prompt of the form In[n] := to tell you that it is ready to receive input.When you have entered your input, Mathematica processes it, and then displays the result with a label of the form Out[n] =.
Different text - based interfaces use slightly different schemes for letting Mathematica know when you have finished typing your input.With some interfaces you press Shift - Return, while in others Return alone is sufficient.

An important feature of Mathematica is its ability to handle formulas as well as numbers. Whenever you use Mathematica, you are accessing the world' s largest collection of computational algorithms. Mathematica knows about all the hundreds of special functions in pure and applied mathematics (e.g., Chebyshev polynomials, Bessel functions).

Example.  The following function computes the 10 th degree Chebyshev polynomial and the next one  draws the function  on the interval [-1, 1].

ChebyshevT[10,x]

Plot[ChebyshevT[10,x],{x,-1,1}]

Let' s what happens when we use the same input in WolframAlpha:


Note the two links at the lower right hand corner: Download as PDF and Live Mathmatica. The first one is obvious. The second one needs the Mathematica Player plugin to be installed.

In general, Mathematica notebooks allow importing and exporting of many formats. One can prepare even a slide show in Mathematica.

Kernel and FrontEnd

Mathematica consists of two independent computational environments called the FrontEnd and the Kernel, which communicate by means of a protocol called MathLink. The Kernel does all the computations. The FrontEnd is what you see in front of you, including the window, menus, etc. You can use many FrontEnds with one Kernel but the usual FrontEnd is what is know a notebook FrontEnd (there are also ASCII front ends you can run using a terminal interface). 

The Kernel is the basic programing environment and in fact it can be used to completely control the FrontEnd. We will give a few examples, but we will not use much of this. For example:

nb1=CreateDocument[{Plot[x^2,{x,-1,1}]}]

ls=Notebooks[]

SelectedNotebook[]

SetSelectedNotebook[ls[[3]]]

The FrontEnd itself can also be “programmed” independently of the Kernel. This will be more important for us later, in building interfaces.

Mathematica notebooks

Mathematica is one of the largest single application programs ever developed, and it contains a vast array of algorithms and important technical innovations. Among these innovations is the concept of platform - independent interactive documents known as notebooks.

Every Mathematica notebook is a complete interactive document combining text, tables, graphics, calculations, and other elements. A Mathematica notebook consists of a list of cells, which you can group (sections etc).

Exercise. Click on different brackets on the right  in this notebook with a right mouse button to find out tge style being used.

Palettes and buttons provide a simple but fully customizable point - and - click interface to Mathematica (for Greek symbols, signs of integral, simple build - in functions, etc).
Recently Wolfram Research has expanded the concept of a notebook by introducing a new document format called CDF (“Computable Document Format”) which unlike traditional notebooks allows interactive “dynamic” content.

The Unifying Idea of Mathematica

Mathematica is built on the powerful unifying idea that everything can be represented as a symbolic expression.

Main Features of Mathematica

Once one starts experimenting in Mathematica, on   immediately notices some of its main features.
1. One important feature of Mathematica that differs from other computer languages, and from conventional mathematical notation, is that function arguments are enclosed in square brackets, not parentheses. Parentheses in Mathematica are reserved specifically for indicating the grouping of terms. There is obviously a conceptual distinction between giving arguments to a function and grouping terms together.
2. Names of build - in functions have their first letters capitalized.
3. Multiplication can be represented by a space.
4. Powers are denoted by^.
5. Numbers in scientific notation are entered, for example, as 2.5*^-4 or 2.5 10^-4.
6. There is a general convention in Mathematica that all function names are spelled out as full English words, unless there is a standard mathematical abbreviation for them. The great advantage of this scheme is that it is predictable. Once you know what a function does, you will usually be able to guess exactly what its name is. If the names were abbreviated, you would always have to remember which shortening of the standard English words was used.
7. Another feature of built - in Mathematica names is that they all start with capital letters. The capital letter convention makes it easy to distinguish built - in objects. If Mathematica used max instead of Max to represent the operation of finding a maximum, then you would never be able to use max as the name of one of your variables. In addition, when you read programs written in Mathematica, the capitalization of built - in names makes them easier to pick out.
8. N is a function that turns exact numbers and certain symbols into approximate numbers. For example:

N[Pi]

N[Sqrt[2],30]

Hence N cannot be used for a function or a variable name. The same is true of some other symbols written with a capital letter (e.g. E,C). For that reason it is important to follow the conventon that user defined symbols begin with a small letter.

A quick access to help information is achieved by typing the question mark :

?FullForm

?Part

The quick access to help is also by highlighting the word and then pressing F1.

To get help for the command/operator you know you need to type ? and the command/operator. If you do not know the operator, search the Help Browser.

?>>

Mathematica understands lists as {a, b, c} (in the full form it is  List[a, b, c]). One can learn later on that many objects in Mathematica are written by using lists. For instance, a matrix can be inserted in the following way: go to the main manu; insert; tables/matrices:

({{\[Placeholder], \[Placeholder], \[Placeholder]}, {\[Placeholder], \[Placeholder], \[Placeholder]}, {\[Placeholder], \[Placeholder], \[Placeholder]}})

Next one just needs to put the brackets and fill in the matrix elements by clicking on each empty square :

(({{1, 2, \[Placeholder]}, {\[Placeholder], \[Placeholder], \[Placeholder]}, {\[Placeholder], \[Placeholder], \[Placeholder]}}))

The result is :

(({{1, 2, 3}, {2, 3, 4}, {5, 6, 7}}))

The same matrix can be inputed like this :

{{1,2,3},{2,3,4},{5,6,7}}

%//MatrixForm

Here % means the last expression.

2+2

%+4

%%+2

Here %% means the last but one expression.

Example.

Plus[Power[x,2],Sqrt[x]]

The same can be inputed by either using palettes or by the following sequence: buttons cntl+2 gives (Sqrt[□]); next one needs to type in "x"; this gives (Sqrt[x]); next +x. To type in the square one can type in alt+6 which ((gives )^□) and then type in 2 in the empty square.

One can type many symbols without using palettes. For instance, to type in π, ome needs to press esc then type in pi then press esc once again.

Example.

The use of Ctrl+6:

(x^2)

esc+i+i+esc

I

esc+pi+esc

π

Alt+7 (applying to the blue bracket on the right): gives text in the notebook.

An overview of programming techniques

For most of the more complex problems that one wants to solve with Mathematica, one has to create Mathematica programs oneself. Mathematica supports several styles of programming, and one is free to choose the one is most comfortable with. However, it turns out that no single type of programming suits all cases equally. As a result, it is useful to learn several different types of programming.

Traditional programming language such as C or Fortran use  procedural programming (assignments and loops such as Do, For, While and so on). They also exist in Mathematica. But while any Mathematica program can, in principle, be written in a procedural way, this is rarely the best approach. In a symbolic system like Mathematica, functional and rule - based programming typically yields programs that are more efficient, and easier to understand.

Some types of programming : 
Procedural Programming
List - based Programming (Many operations are automatically threaded over lists, starting point to learn).
Functional Programming
Rule - Based Programming
Mixed Programming Paradigms

There are typically many different ways to formulate a given problem in Mathematica. In almost all cases, however, the most direct, precise and simple formulations will be best.

There are dozen of definitions of the factorial function (see later on).

Expressions

All objects in Mathematica programming language are expressions. For example

a+b

{2,3,5}

StringTake["hello",4]

Sin[x]

sin(π)

First[{a,b,c}]

are all different kinds of expressions.  These expressions often look like mathematical formulas (more about that later), which makes them more understandable and memorable to humans, but actually that have an internal form that is very simple and very consistent. It is called the “Full Form” of an expression and can be seen by applying the function FullForm to it (but there is a caveat, see below).

FullForm of expressions

Each expression is either an Atom or has the form

F[a1,a2,...,an]

where F is called the Head of the expression and a1, a2, are expressions. Examples of atoms are  2,a,3/4,3.2, "cat". Whether something is an atom can be tested with the function AtomQ:

AtomQ[2]

AtomQ[{2,3}]

Expressions often do not look like the above, for example  a+b, however they all have FullForm, which does

FullForm[a+b]

Head[a+b]

Head[a]

Head[2]

FullForm[{a,b}]

Head[{a,b}]

Note that atoms also have Head:

Head[2]

Head["cat"]

Head[cat]

Note also that :

Head[x]

x=1

x+2

Head[x]

Evaluation of x to 1 caused the Head to come put as Integer. You can see the original Head by preventing evaluating e.g.

Head[Unevaluated[x]]

2+3

FullForm[Hold[2+3]]

ReleaseHold[%]

The full form of

x=1

is

FullForm[Hold[x=1]]

Clear[x]

It is important to distinguish the assignment Set from Equal, which is usually written as == and has

FullForm[Hold[x==1]]

Clear[x]

x==1

x=1;

x==2

Clear[x]

Parts of Expressions

A very important skill is extracting parts of expressions. An expression is really a tree-like object, as can be seen using the function TreeForm:

?TreeForm

g=a+(b^2)+(c^3)+d;

FullForm[g]

TreeForm[g]

Level[g,{1}]

Level[g,{2}]

Part[g,0]

g[[1]]

g[[2]]

g[[3]]

g[[3,3]]

g[[2,2]]

g[[2,0]]

and so on.

You can also do this from the back :

g[[-2,1]]

g

g[[1;;3]]

a + b^2 + c^3

g[[2;;4]]

Now, here comes a very nice and important fact: you can change an expression by an assignment to a part of it. For example;

g[[1]]=x+y;

g

g[[3;;4]]=z;g

List, Vectors, Matrices, Tensors

A very important thing to notice that in Mathematica lists are just expressions with Head List:

m={a,b,c,d};

Length[m]

List[a,b,c,d]

A matrix is simple a list of lists of the same length:

mat={{a,b,d},{c,d,e}}

mat[[1,1]]

mat[[2,2]]

mat[[All,1]]

mat[[All,2]]

mat[[1,All]]

mat[[2,All]]

We will later see how to easily create arbitrarily large matrices using the functions Table and Array.

Table[(i^2),{i,1,10}]

Table[i *j,{i,1,5},{j,1,5}]

A note on forms of expressions.

We already know that a Mathematica expression often looks different to human eyes than its internal form (FullForm). However, the situation is made more complicated, by the fact that traditional mathematical notation is not unambiguous. Because of this  and for reasons of history Mathematica has several “forms” of input and output.  The first versions of Mathematica has only two forms: InputForm, which looked like a standard programming language (e.g. Fortran) way of writing mathematical formulas and OutputForm, which is a little More like usual mathematics and has become completely obsolete (it retained only for reasons of compatibility with very early Mathematica notebooks). Since then they have both been replaced by StandardForm and TraditionalForm. StandardForm retains the basic principles of InputForm but allows more usual mathematical expressions. TraditionalForm looks almost like usual mathematical notation. One can convert between these forms using the Convert To sub menu in the Cell menu. One can also set the default forms for the Input and Output in the Preferences menu.

Basic principles of InputForm (and StandardForm)

1. All built in functions start with a capital letter.

2. Square brackets [] are used as function brackets.

3. (InputForm) The basic arithmetical operations are denoted by + (addition),* or space (multiplication) / (division), ^ (power).

4.  There are the following inclusions InputForm ⊂ StandardForm ⊂ TraditionalForm but not in the opposite direction.

Links

http://reference.wolfram.com/Mathematica/guide/Expressions.html

MouseOver

2. Working with Lists

Expressions

Lists

One of the most common expressions in Mathematica are lists.

Solve[(x^3)==1,x]

% // N

CoefficientList[a x^2 + b x + c, x]

Options[Plot]

Let us also recall that the matrix is inputed by using lists :

{{1, 2, 3}, {2, 3, 4}, {34, 5, 3}} // MatrixForm

Let us learn  how to generate lists and what basic operations one can perform with them.  Another useful command is Table

Table[i^2 + 2, {i, -1, 2}]

% // TableForm

One can generate not only numbers but also other expressions :

Array[a, 3]

Some commonly used objects are already defined in Mathematica. For instance, the identity matrix :

IdentityMatrix[3] // MatrixForm

For the matrices Mathematica has a lot of build - in operations

Eigenvalues[{{1, 2}, {3, 2}}]

Eigenvectors[{{1, 2}, {3, 2}}]

Basic operations for the lists include the following :

{1, 2, 3} + {1, 2, 3}

{1, 2, 3} + 1

A scalar product is given by a dot

{a, b, c}.{s, d, f}

However, one needs to be careful with length of the objects.

{1, 2, 3} + {1, 2, 3, 4}

Other useful operations include

Prepend[{a, b, c}, d]

Append[{a, b, c}, d]

Union[{a, b, c}, {a, b, d}]

Join[{a, b, c}, {a, b, d}]

Take[{a, b, c, e}, 2]

Also have a look at commands Insert, Delete and many others in the help. The name of the command suggests unambiguously what it performs with a given list.

To get an element of the list one indicates its position.

{a, b, c}[[1]]

{a, b, c, d}[[-1]]

Here - 1 means the first elemend counted from the end.

{a, b, c, d}[[2]]

If you do not know how many elements are in the list, you can always verify this by using Length

Length[{a, b, v}]

Length[{a, b, {v, w}}]

A similar command for the dimension of the list is Dimensions

Dimensions[{a, b, {v, w}}]

Dimensions[{{a, b}, {v, w}}]

This counts the elements of the first level in the list.

In applications one often encounters the problem to verify whether a given element is in the list and if so, one might require further its position.

Position[{{a, b, c}, {a, f, g}}, a]

Here in the answer one has a position taking into account  the nested lists

Since the lists can be nested, it is useful to know that they can always be flattened.

?Flatten

{{a, b, c}, {a, f, g}} // Flatten

To get rid of repeated elements one uses Union

% // Union

From a given list one can get a list of permutations and other lists of a given length with all elements of the original list

Permutations[{a, b, c}]

Tuples[{0,1},3]

Accumulate[{a,b,c,d,e,f}]

Apply and Map

?Apply

Let us form a new ecpression from the list and the other way round.

FullForm[{a,b,c}]

Times@@{a,b,c}

FullForm[a b c]

List@@(a b c)

Another example is

Plus@@{a,b,c}

A more complicated example is to generate a list of coefficients (maybe useful for polynomial expressions)

Subscript[A,#]&/@Table[i,{i,1,10}]

Here /@ means Map.

?Map

Here there is a trivial example of forming a list.

((#)^2)&/@Table[i,{i,1,10}]

k=Table[i,{i,1,10}]

Therefore, the command /@ works as follows. It substitutes every element of the list k into the function F[#] = #^2 where # stands for an argument.

Evaluation

A very important concept in Mathematica is that of evaluation. In Mathematica evaluation always takes place after you write some input and press Shift + Enter. The process of evaluation is quite complicated, and follows a definite sequence of steps. Understanding this process is important in advanced Mathematica programming and we will return to this in the future.  Often the evaluation process takes place even if nothing seems to happen. For example:

FullForm[Hold[2/3]]

(2/3)

FullForm[2/3]

2+3 I

FullForm[Hold[2+3I]]//InputForm

FullForm[2+3 I]

AtomQ[Complex[2,3]]

Head[Unevaluated[2+3I]]

Head[2+3I]

An interesting special case are graphics.

gr=Plot[(x^2),{x,-1,1}]

InputForm[gr]

We  see that a graphic is also a Mathematica object. (You will obtain a simpler expression if you look at InputForm[gr]).  One can therefore use the Mathematica programing language to control every detail of a graphic. Graphic programming in Mathematica is a whole big subject, but we will see a few examples later on.

It is possible to think of Mathematica as an algebraic object, somewhat like a ring, with partial addition and multiplication, but also with

(2^gr)

{1,2,3}+1

{1,2,3}+{1,3}

Distribute[("cat"+"dog")*"mouse"]

The evaluation loop.

When you enter an input expression Mathematica’s Kernel evaluates in a very definite order. Understanding this order is important for Mathematica programming. The evaluation order will be described carefully later, once we learn about rules and patterns. However, the basic idea is this: Mathematica evaluates each part of the expression by turn, starting with the Head.  It applies all rules it knows for the expression, first user defined then built in ones, until it can no longer find a rule. Then it stops and “returns” the result. (Sometimes this evaluation will not stop and we get into an infinite loop. Actually Mathematica will almost always detect such situations and will stop, unless we change the defaults to make it run for ever).

Programming using Patterns and Rules

Mathematica allows many different styles of programming. There is one style that, although not quite unique to Mathematica, distinguishes it form other similar systems. This is the possibility of using "patterns" and "re-write rules" or just "rules". 
The basic concept in this kind of programming are that of a "rule" and "pattern".  Rules can be local and global.

Local Rules

A local rule always has the form

?Rule

or

?RuleDelayed

Note that:

FullForm[lhs->rhs]

FullForm[lhs:>rhs]

The difference between Rule and RuleDelayed will be explained below. Most often Rule is used together with the function ReplaceAll (see also Replace):

?ReplaceAll

Here are some examples of using  rules:

(x^2)+Sin[x y]+3/.{x->π,y->2 π}

Now we use a more general rule. This time we use a "pattern"

(x^2)+Sin[x y]+3/._->π

?_

The reason for the above result is that ReplaceAll starts looking for a match for a pattern from the top level of the expression and

Replace[(x^2)+Sin[x y]+3,_->π,{3}]

Level[(x^2)+Sin[x y]+3,{4}]

Replace[(x^2)+Sin[x y]+3,_->π,{2}]

(x^2)+Sin[x y]+3/.Sin[x_]:>Sin[x^2]

(x^2)+Sin[x y]+3/._?(#>2&)->π

(x^2)+Sin[x y]+3/.a_/;a>2->Pi

(x^2)+Sin[x y]+3/._?(AtomQ[#]&)->π

(x^2)+Sin[x y]+3/.x_Times->π/4

FullForm[(x^2)+Sin[x y]+3]

(x^2)+Sin[x y]+3/._Power->π/4

These examples illustrate some of the very many ways of forming patterns in Mathematica. The most basic pattern is x_ which stands for anything that is (locally) assigned the name x.

Here is an example where Rule and RuleDelayed give different answers:

a=0;

Sin[2]/.a_Integer->(a^2)

Sin[2]/.a_Integer:>(a^2)

Before using a rule it is a good idea to look at the FullForm of an expression.

Here are some traps.

Clear[a]

(Sqrt[2])+(1/(Sqrt[2]))/.(Sqrt[2])->a

FullForm[(Sqrt[2])+(1/(Sqrt[2]))]

Unevaluated[(Sqrt[2])+(1/(Sqrt[2]))]/.HoldPattern[(Sqrt[2])]->a

(Sqrt[2])+(1/(Sqrt[2]))/. 2^Rational[x_,y_]->a^x

(Sqrt[2])+(1/(Sqrt[2]))/.{(Sqrt[2])->a,(1/(Sqrt[2]))->1/a}

Rule based programming is very convenient when dealing with graphics.

gr=Disk[{0,0},1]

Graphics[gr,ImageSize->Small]

Graphics[{Red,gr},ImageSize->Tiny]

Graphics[{Red,gr},ImageSize->{100,100}]/.Disk->Circle

gr2=PolarPlot[Sin[3 θ],{θ,0,(π/3)},ImageSize->Small]

gr2/.Line->Polygon

Many Mathematica functions return a list of rules as the output.

rules=Solve[(x^3)+3x+4==0,x]

Note that this is actually a list of lists, each containing one rule.

This is very convenient, because we can use ReplaceAll to substitute these rules into other formulas. For example:

x/.rules

(x^3)+3x+4/.rules//Simplify

Simplify[%]

Here is a similar example with FindRoot instead of Solve

FindRoot[x (E^(-x))==0.2,{x,0.1}]

x Exp[-x]==0.2/.%

Links

http : // reference.wolfram.com/mathematica/tutorial/PatternsAndTransformationRules.html

Global Rules ("Functions")

Here is one way to define  a "function" in Mathematica:

Clear[f]

f[x_]:=(x^2)

f[I]

Clear[a]

f[a]

f[3]

?f

DownValues[f]

Although  people often call f defined in this way a function, actually it is only a "global rule". More precisely, when a definition of this kind is evaluated Mathematica creates a rule for the symbol f, which it uses every time when f is used. The rule is stored as a DownValue of f:

DownValues[f]

Here x_ is a "pattern", which stands for "anything", with a temporary name "x". The rule says "change f(anything) to (anything^2)". HoldPattern prevents evaluation of f(x_) (which would otherwise be replaced by ((x_)^2) but  f[x_] is treated as a pattern for matching purposes.

So what happens when we evaluate definitions of this kind is this:  Mathematica makes certain rules, stores them, and then applies them in a certain order. Here is an example:

Clear["Global`*"]

f[x_Real]:=3

f[1]:=2

f[x_Symbol]:=(x^2)

f[x_Integer]:=5

DownValues[f]

DownValues[f]=Rest[DownValues[f]]

DownValues[f]

f[2/3]

f[x_]:=0

f["cat"]

f[1]

f[x_]:=0

f["dog"]

Clear[f]

DownValues[f]

f[2]

f[7]

f[1.1]

f[a]

f["cat"]

Map[f,{.5,1,a}]

The order in which rules are applied by Mathematica is roughly determined by two facts; more specific rules are applied before more general rules, and rules of equal generality are applied in the order they are entered.

In addition to DownValues there are also OwnValues and UpValues  (and some other Values) created as follows:

Clear[a]

a=1;OwnValues[a]

ClearAll[b];

b/:Sin[b]=2;

b/:Cos[b]=2;

(cos^2)(b)+(sin^2)(b)

UpValues[b]

When a  expression is evaluated Mathematica uses the rules contained in UpValues, DownValues, and so on in a certain order before it uses its built-in rules, and evaluates expressions until it stops changing. Note also that certain built in rules are applied by Mathematica automatically on evaluation but others require using a special function such as Simplify or FullSimplify. For example the transformation

Clear[a]

(a^n)(a^m)

while

((cos(α))^2)+((sin(α))^2)

does not automatically simplify to 1 but

Simplify[(cos^2)(b)+(sin^2)(b)]

Some simplifications only work with specific assumptions:

Simplify[(Sqrt[(x^2)])]

Assuming[x≥0,Simplify[(Sqrt[(x^2)])]]

Assuming[x<=0,Simplify[(Sqrt[(x^2)])]]

Finally, Mathematica as a rule tries to apply any transformations it know to an expression until it no longer changes.  However, this is not the case when we use a replacement rule using ReplaceAll.  ReplaceAll looks for patterns in all the parts of an expression, but only looks for one match in each part. So, if we have only more than one rule, we may not obtain all the transformations we wish to get:

rules={Log[x_ y_]:>Log[x]+Log[y],Log[x_^k_]:>k Log[x]};

Log[(Sqrt[a(((b (c^d)))^e)])]/.rules

In order to obtain all transformations we should use ReplaceRepeated (//.) instead of ReplaceAll (/.).

Log[(Sqrt[a(((b (c^d)))^e)])]//.rules

Another important thing: Options of Mathematica's functions are given as Rules.

Plot[(x^2),{x,0,1}]

Options[Plot]

Plot[(x^2),{x,0,1},Axes->False,Frame->True,GridLines->Automatic,PlotStyle->{Red,Dashing[0.01]}]

The difference between := and =

The difference between :=and= is exactly the same as that between :> and ->. Note these FullForms:

FullForm[Hold[a=3]]

FullForm[Hold[a:=3]]

Consider the following two definitions:

f[p_]:=Expand[p]

g[p_]=Expand[p];

?=

?:=

If we apply them to an expression like (((a+b))^3) we will get quite different results:

f[(((a+b))^3)]

g[(((a+b))^3)]

The reason is that = evaluates the right hand side before assigning the evaluated value to the left hand side, while := assigns the unevaluated right hand side to the left hand side.

Here is another example of the difference.

Clear[x]

?x

x=x+1

Clear[x]

x:=x+1

x

Clear[x]

?x

x=1;x=x+1

Clear[x]

x=1;x:=x+1

x

Links

http : // reference.wolfram.com/mathematica/tutorial/ManipulatingValueLists.html

http : // reference.wolfram.com/mathematica/tutorial/ManipulatingOptions.html

Functions that take Functions as arguments

In functional programming a very important role is played by functions that take functions as arguments. The most important of these are Map and Apply:

Clear[f]

Map[f,{a,b,c,d}]

Map[f,(x^2)(y^3)]

Map[f,(x^2)(y^3),{1}]

Map[f,(x^2)(y^3),{2}]

Apply[f,g[x,y]]

Apply[Plus,x*y]

Apply[Times,x+y]

Apply[Times,Unevaluated[2+3]]

Apply[f,g[h[x],k[y]],{1}]

Short notation:

Map[f,expr]

f/@expr

Apply[f,expr]

f@@expr

Attributes and Listability

The behavior of Mathematica functions and global rules is affected by so called Attributes. Each built in function has some attributes, for example

Attributes[Sin]

Attributes[Plus]

The most important attribute of functions is the attribute Listable. Let's explain briefly what it does.

Clear[f]

ls=Range[10]

Map[f,ls]

If we give f the Attribute Listable we will not need to use Map.

SetAttributes[f,Listable]

f[ls]

In addition

f[{a,b},{c,d}]

f[a,{b,c}]

The attribute Listable of Plus is the reason for the following behavior:

{1,2,3}+{4,5,6}

1+{2,3,4,5}

The attributes Orderless, Flat and OneIdentity are interesting, but complicated. Let’s just see and illustration

ClearAll[f]

f[a,b]/.f[b,x_]->g

SetAttributes[f,Orderless]

f[a,b]/.f[b,x_]->g

f[a,b,c]/.f[a,f[b,c]]->g

SetAttributes[f,Flat]

f[a,b,c]/.f[a,f[b,c]]->g

ClearAll[f]

Another group of important attributes are HoldFirst, HoldAll, HoldRest

Attributes[Set]

Attributes[SetDelayed]

ClearAll[f]

SetAttributes[f,HoldFirst]

f[x_,y_]:=(x=y^2)

x=3;

f[x,2];

x

Links

http : // reference.wolfram.com/mathematica/tutorial/PureFunctions.html

http : // reference.wolfram.com/mathematica/tutorial/ApplyingFunctionsToListsAndOtherExpressions.html

http : // reference.wolfram.com/mathematica/tutorial/Attributes.html

http : // reference.wolfram.com/mathematica/tutorial/SelectingPartsOfExpressionsWithFunctions.html